﻿
package com.danielsheldon.utils.displayListMonitor
{
	import flash.net.LocalConnection;
	import flash.events.StatusEvent;
	import flash.events.Event;
	import flash.display.Stage;
	import flash.display.DisplayObject;
	import flash.utils.getTimer;

	public class DisplayListMonitor
	{
		private var _conn:LocalConnection;
		private var _curPage:Number = 0;
		private var _children:String = "";
		private var _outputArray = new Array();		private var _target:DisplayObject;
		private var _msgNum:Number = 0;
		public function DisplayListMonitor(target:DisplayObject)
		{
			_target = target;
			_conn = new LocalConnection();
			_conn.addEventListener(StatusEvent.STATUS, statusHandler);
			_conn.send("DLMConnection", "DLMHandler", "DLM", "DLM Instantiated", getTimer(), _msgNum);
			_msgNum++;
			target.addEventListener(Event.ADDED, showChildren, true);
			target.addEventListener(Event.REMOVED, showChildren, true);
			target.addEventListener(Event.ADDED_TO_STAGE, showChildren, true);
			target.addEventListener(Event.REMOVED_FROM_STAGE, showChildren, true);
		}
		function showChildren(e:Event)
		{
			_children = _msgNum + " :: " + e.type + " :: " + e.target.name + " :: " + getTimer() + "ms\n\n";
			_outputArray.push(getChildren(_target, ""));
			var tmp:String = "";
			tmp = _outputArray[_outputArray.length - 1]
			_curPage = _outputArray.length - 1;
			_conn.send("DLMConnection", "DLMHandler", e.type, tmp, getTimer(), _msgNum);
			_msgNum++;
		}
		function getChildren(obj, seperator:String)
		{
			for (var i:int = 0; i<obj.numChildren; i++)
			{

				var child:DisplayObject = obj.getChildAt(i);
				var childName:String = "null";
				try
				{
					childName = child.name;
				}
				catch (e)
				{

				}
				_children += seperator + i + " :: " + childName + " :: " + child + " :: " + "\n";
				try
				{
					getChildren(child, seperator+"    ");
					_children += seperator + "    " + "---------------\n";
				}
				catch (e)
				{
				}
			}
			return _children;
		}
		private function statusHandler(e:StatusEvent)
		{
			switch (e.level)
			{
				case "status" :
					//trace("LocalConnection.send() succeeded");
					break;
				case "error" :
					trace("LocalConnection.send() failed");
					break;
			}

		}

	}
}